package cn.itcast.order.service;


import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.pojo.User;
import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@DefaultProperties(defaultFallback = "allMethodFallback")
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand
    public String queryOrderById(Long orderId) {
//         1.查询订单
        Order order = orderMapper.findById(orderId);
//        2.远程调用用户微服务，返回User对象http://localhost:8081/user/1
        User u = restTemplate.getForObject("http://userservice/user/"+order.getUserId(), User.class);
//        3.把用户user对象set到Order对象中
        order.setUser(u);
//         4.返回
        return JSON.toJSONString(order);
    }
//    @Autowired
//    private UserClient userClient;
//
//    public String queryOrderById(Long orderId) {
//        // 1.查询订单
//        Order order = orderMapper.findById(orderId);
//        //        2、查询用户
//        //        User user = restTemplate.getForObject("http://userservice/user/" + order.getUserId(), User.class);
//        User user = userClient.findById(order.getUserId());
//        //        3、set到order的属性中
//        order.setUser(user);
//        // 4.返回
//        //        return order;
//        return JSON.toJSONString(order);
//    }

    public String queryOrderByIdFallback(Long orderId){

        return "******************************服务器在游离中*****************************";
    }

    public String allMethodFallback(){
        return "*****************************************************************************";
    }

}
